﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CivilRegistry.ControlledModel;
using CivilRegistry.UserControls;
using System.IO;
using CivilRegistry.Common;

namespace CivilRegistry
{
    public partial class Profile : System.Web.UI.Page
    {
        ControlledModel.User loggedInUser = null;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (SessionHandler.CurrentSession.User == null)
            {
                Response.Redirect("~/Login.aspx?&redirect=Profile.aspx");
            }
            else if (SessionHandler.CurrentSession.User is Admin || SessionHandler.CurrentSession.User is Hospital)
            {
                btnEdit.Visible = false;
                btnProfileCancel.Visible = false;
            }

            SiteMaster masterPage = (SiteMaster)Page.Master;
            masterPage.SelectedMenu = "Profile";

            this.loggedInUser = SessionHandler.CurrentSession.User;

            if (!Page.IsPostBack)
            {
                this.LoadUserValues(this.loggedInUser);
                pnlDisplay.Visible = true;
                pnlEdit.Visible = false;
            }
        }

        protected void lbChangeImage_Click(object sender, EventArgs e)
        {
            if (ImageUploader.HasFile)
            {
                this.loggedInUser.SetProfileImage(ImageUploader.FileContent);
                this.loggedInUser.SaveChanges();
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            this.LoadEditUserValues(this.loggedInUser);
            pnlDisplay.Visible = false;
            pnlEdit.Visible = true;
        }

        private void LoadEditUserValues(ControlledModel.User user)
        {
            txtEmailAddress.Text = user.EmailAddress;
            txtPhoneNo.Text = user.PhoneNo.ToString();
            txtFirstName.Text = user.FirstName;
            txtMiddleName.Text = user.MiddleName;
            txtLastName.Text = user.LastName;
            txtMotherName.Text = user.MotherName;
            txtFatherName.Text = user.FatherName;
            txtGaurdianName.Text = user.GaurdianName;

            if (!string.IsNullOrEmpty(user.Gender) && user.Gender != " ")
            {
                rblGender.SelectedValue = user.Gender;
            }

            ((TextBox)ucPermanentAddress.FindControl("txtAddress")).Text = user.PermanentAddress.Address;
            ((TextBox)ucPermanentAddress.FindControl("txtPIN")).Text = user.PermanentAddress.PIN.ToString();
            ((DropDownList)ucPermanentAddress.FindControl("ddlStateName")).SelectedIndex = user.PermanentAddress.District.State.StateId;
            var ddlDistrictName = ((DropDownList)ucPermanentAddress.FindControl("ddlDistrictName"));
            ddlDistrictName.DataSource = District.FindAllByStateId(user.PermanentAddress.District.State.StateId);
            ddlDistrictName.DataBind();
            ddlDistrictName.SelectedValue = user.PermanentAddress.District.DistrictId.ToString();
            ((TextBox)ucPermanentAddress.FindControl("txtCity")).Text = user.PermanentAddress.City;

            if (user.PresentAddress != null)
            {
                ((TextBox)ucPresentAddress.FindControl("txtAddress")).Text = user.PresentAddress.Address;
                ((TextBox)ucPresentAddress.FindControl("txtPIN")).Text = user.PresentAddress.PIN.ToString();
                ((DropDownList)ucPresentAddress.FindControl("ddlStateName")).SelectedIndex = user.PresentAddress.District.State.StateId;
                ddlDistrictName = ((DropDownList)ucPresentAddress.FindControl("ddlDistrictName"));
                ddlDistrictName.DataSource = District.FindAllByStateId(user.PresentAddress.District.State.StateId);
                ddlDistrictName.DataBind();
                ddlDistrictName.SelectedValue = user.PresentAddress.District.DistrictId.ToString();
                ((TextBox)ucPresentAddress.FindControl("txtCity")).Text = user.PresentAddress.City;
            }
        }

        private void LoadUserValues(ControlledModel.User user)
        {
            lblUserIdValue.Text = user.UserId.ToString();
            lblUserNameValue.Text = user.UserName;
            lblFirstNameValue.Text = user.FirstName;
            lblMiddleNameValue.Text = user.MiddleName;
            lblLastNameValue.Text = user.LastName;
            lblMotherNameValue.Text = user.MotherName;
            lblFatherNameValue.Text = user.FatherName;
            lblGaurdianNameValue.Text = user.GaurdianName;
            lblEmailAddressValue.Text = user.EmailAddress;
            lblPhoneNoValue.Text = user.PhoneNo.ToString();

            if (user.Gender == "M")
            {
                lblGenderValue.Text = "Male";
            }
            else if (user.Gender == "F")
            {
                lblGenderValue.Text = "Female";
            }

            lblDateOfBirthValue.Text = user.DateOfBirth.ToString();
            lblAgeValue.Text = user.Age.ToString();
            lblAddressValue.Text = user.PermanentAddress.Address;
            lblPINValue.Text = user.PermanentAddress.PIN.ToString();
            lblCityValue.Text = user.PermanentAddress.City;
            lblStateNameValue.Text = user.PermanentAddress.District.State.StateName;
            lblDistrictNameValue.Text = user.PermanentAddress.District.DistrictName;

            if (!File.Exists(user.GetPermanentAddressElectricalBillFilePath()))
            {
                lbnViewElectricBillXerox.Visible = false;
            }
            else
            {
                lbnViewElectricBillXerox.Visible = true;
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            this.loggedInUser.EmailAddress = txtEmailAddress.Text;
            this.loggedInUser.PhoneNo = Convert.ToInt64(txtPhoneNo.Text);

            if (((TextBox)ucPermanentAddress.FindControl("txtAddress")).Text != "")
            {
                PermanentAddress permanentAddress = this.loggedInUser.PermanentAddress ?? new PermanentAddress();

                permanentAddress.Address = ((TextBox)ucPermanentAddress.FindControl("txtAddress")).Text;
                permanentAddress.PIN = (Convert.ToInt32(((TextBox)ucPermanentAddress.FindControl("txtPIN")).Text));
                permanentAddress.District = District.FindById(Convert.ToInt32(((DropDownList)ucPermanentAddress.FindControl("ddlDistrictName")).SelectedValue));
                permanentAddress.District.State = State.FindById(Convert.ToInt32(((DropDownList)ucPermanentAddress.FindControl("ddlStateName")).SelectedValue));
                permanentAddress.City = ((TextBox)ucPermanentAddress.FindControl("txtCity")).Text;

                this.loggedInUser.PermanentAddress = permanentAddress;
            }

            if (((TextBox)ucPresentAddress.FindControl("txtAddress")).Text != "")
            {
                PresentAddress presentAddress = this.loggedInUser.PresentAddress ?? new PresentAddress();

                presentAddress.Address = ((TextBox)ucPresentAddress.FindControl("txtAddress")).Text;
                presentAddress.PIN = (Convert.ToInt32(((TextBox)ucPresentAddress.FindControl("txtPIN")).Text));
                presentAddress.District = District.FindById(Convert.ToInt32(((DropDownList)ucPresentAddress.FindControl("ddlDistrictName")).SelectedValue));
                presentAddress.District.State = State.FindById(Convert.ToInt32(((DropDownList)ucPresentAddress.FindControl("ddlStateName")).SelectedValue));
                presentAddress.City = ((TextBox)ucPresentAddress.FindControl("txtCity")).Text;

                this.loggedInUser.PresentAddress = presentAddress;
            }

            FileUpload electricityBillUploader = ((FileUpload)ucPermanentAddress.FindControl("FlupldElectricitybill"));
            if (electricityBillUploader.PostedFile.FileName != "")
            {
                if (electricityBillUploader.PostedFile.FileName.ToLowerInvariant().EndsWith(".pdf"))
                {
                    electricityBillUploader.SaveAs((this.loggedInUser).GetPermanentAddressElectricalBillFilePath());
                }
                else
                {
                    lblStatus.Text = "Please upload a valid file. Note: The file should be in pdf format.";
                    return;
                }
            }

            electricityBillUploader = ((FileUpload)ucPresentAddress.FindControl("FlupldElectricitybill"));
            if (electricityBillUploader.PostedFile.FileName != "")
            {
                if (electricityBillUploader.PostedFile.FileName.ToLowerInvariant().EndsWith(".pdf"))
                {
                    electricityBillUploader.SaveAs((this.loggedInUser).GetPresentAddressElectricalBillFilePath());
                }
                else
                {
                    lblStatus.Text = "Please upload a valid file. Note: The file should be in pdf format.";
                    return;
                }
            }

            try
            {
                this.loggedInUser.SaveChanges();
            }
            catch (ApplicationException ex)
            {
                lblStatus.Text = ex.Message;
                return;
            }
            catch (Exception ex)
            {
                Logger.ErrorLogger.Log(ex);
                lblStatus.Text = "We are sorry...an unexpected error occurred on the application. Please contact the administrator for more information.";
                return;
            }

            lblStatus.Text = "Changes saved successfully.";

            this.LoadUserValues(this.loggedInUser);

            pnlDisplay.Visible = true;
            pnlEdit.Visible = false;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            pnlEdit.Visible = false;
            pnlDisplay.Visible = true;
        }

        protected void btnProfileCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Default.aspx");
        }

        protected void lbnViewElectricBillXerox_Click(object sender, EventArgs e)
        {
            string electricBillRelativePath = @"~\" + this.loggedInUser.GetPermanentAddressElectricalBillFilePath().Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
            Response.Redirect(electricBillRelativePath);
        }
    }
}